package com.zzg.lucene;

import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.LongPoint;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TermRangeQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.BytesRef;

public class SearchStringField {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		Directory directory = new RAMDirectory();
		IndexWriter indexWriter = new IndexWriter(directory, new IndexWriterConfig(new StandardAnalyzer()));
		Document document = new Document();
		Field stringField = new StringField("string", "11", Store.YES);
		document.add(stringField);
		indexWriter.addDocument(document);
		stringField = new StringField("string", "12", Store.YES);
		document.add(stringField);
		stringField = new StringField("string", "13", Store.YES);
		document.add(stringField);
		stringField = new StringField("string", "14", Store.YES);
		document.add(stringField);
		indexWriter.addDocument(document);
		indexWriter.close();

		// 检索
		IndexSearcher indexSearcher = new IndexSearcher(DirectoryReader.open(directory));
		// 精确查询
		Query query = new TermQuery(new Term("string", "11"));
		ScoreDoc[] scoreDocs = indexSearcher.search(query, 10).scoreDocs;
		for (ScoreDoc scoreDoc : scoreDocs) {
			System.out.println("精确查询：" + indexSearcher.doc(scoreDoc.doc));
		}
		// 范围查询，不包含边界
		query = new TermRangeQuery("string",new BytesRef("11".getBytes()),new BytesRef("12".getBytes()),true,false);
		scoreDocs = indexSearcher.search(query, 10).scoreDocs;
		for (ScoreDoc scoreDoc : scoreDocs) {
			System.out.println("不包含边界：" + indexSearcher.doc(scoreDoc.doc));
		}
		// 范围查询，包含边界
		query = new TermRangeQuery("string",new BytesRef("11".getBytes()),new BytesRef("12".getBytes()),true,true);
		scoreDocs = indexSearcher.search(query, 10).scoreDocs;
		for (ScoreDoc scoreDoc : scoreDocs) {
			System.out.println("包含边界：" + indexSearcher.doc(scoreDoc.doc));
		}
		// 范围查询，左包含，右不包含
		query =  new TermRangeQuery("string",new BytesRef("11".getBytes()),new BytesRef("12".getBytes()),false,false);
		scoreDocs = indexSearcher.search(query, 10).scoreDocs;
		for (ScoreDoc scoreDoc : scoreDocs) {
			System.out.println("左包含右不包含：" + indexSearcher.doc(scoreDoc.doc));
		}
	
	}

}
